<?php
class PXFRecord
{
	private $relations = array();
	protected $fields = array();
	public $model = null;
	
	public function __construct($model,$fields)
	{
		$this->model = $model;
		$this->fields = $fields;
	}
	
	public function __get($arg)
	{
		if(array_key_exists($arg,$this->fields))
		{
			return $this->fields[$arg];
		}
		elseif(array_key_exists(sprintf('%s_%s',$arg,PXFInstance::$lang),$this->fields))
		{
			return $this->fields[sprintf('%s_%s',$arg,PXFInstance::$lang)];
		}
		elseif(in_array($arg,array_keys($this->relations)))
		{
			return $this->relations[$arg];
		}
		elseif(in_array($arg,array_keys($this->model->relations)))
		{
			$this->relations[$arg] = PXFRelationFactory::getInstance($this,$arg,$this->model->relations[$arg]);
			return $this->relations[$arg];
		}	
		else
		{
			echo '<br />';
			echo '<pre>';
			echo 'ATTR: ' . $arg . "\n";
			print_r($this);
			throw new Exception(sprintf('%s has not attribute %s',$this,$arg),1); 
			echo '</pre>';
		}
	}

	public function __set($arg,$value)
	{
		if(array_key_exists($arg,$this->fields))
		{
			$this->fields[$arg] = $value;
		}
		elseif(array_key_exists(sprintf('%s_%s',$arg,PXFInstance::$lang),$this->fields))
		{
			$this->fields[sprintf('%s_%s',$arg,PXFInstance::$lang)] = $value;
		}

	}

	public function __call($method,$args)
	{
		if(!$this->isNew() && in_array($method,array_keys($this->model->relations)))
		{
			$this->relations[$method] = PXFRelationFactory::getInstance($this,$method,$this->model->relations[$method]);
			if(count($args) > 0)
				return $this->relations[$method]->load($args[0]);
			else
				return $this->relations[$method]->load(array());
		}	
	}

	public function __toString()
	{
		return sprintf('%s',$this->model);
	}

	public function isNew()
	{
		return $this->id == null;
	}

	public function save($fields = null)
	{
		$db = PXFDataBase::getInstance();
		if($this->isNew())
		{
			$this->id = 'NULL';
			$query = PXFSQLBuilder::insert($this->model,$this->fields);
			$this->id = $db->insert($query);
		}
		else
		{

			$condition =  new PXFCondition('id',$this->id);
			if($fields != null)
			{
				$update = array();
				foreach($fields as $value)$update[$value] = $this->fields[$value];
				$query = PXFSQLBuilder::update($this->model,$update);
			}
			else
			{
				$query = PXFSQLBuilder::update($this->model,$this->fields);
			}
			$query.= PXFSQLBuilder::whereByConditions($condition);
			$db->update($query);
			$this->id = $this->id; 
			return $this->id;
		}
	}

	public function delete()
	{
		$db = PXFDataBase::getInstance();
		$condition = new PXFCondition('id',$this->id);
		$query = PXFSQLBuilder::delete($this);
		$query .= PXFSQLBuilder::whereByConditions($condition);
		$db->query($query);
		unset($this);
	}

	public function count($args = array())
	{
		$query = PXFSQLBuilder::count($this);
		$query .= PXFSQLBuilder::parseArgs($args);
		$result = $db->select($query); 
		$count = $db->fetch($result);
		return $count['total'];
	}
}
?>
